package config

import (
	"os"

	"github.com/google/uuid"
	"gopkg.in/yaml.v3"
)

type EndPointConfig struct {
	Id       string
	Name     string `yaml:"name"`
	Addr     string `yaml:"addr"`
	Password string `yaml:"password"`
}

type ServerConfig struct {
	ListenAddr    string           `yaml:"listenAddr"`
	LinkSaasAddr  string           `yaml:"linkSaasAddr"`
	ProjectIdList []string         `yaml:"project"`
	EndPointList  []EndPointConfig `yaml:"endPoint"`
}

func (cfg *ServerConfig) completeEndPointId() {
	for i, ep := range cfg.EndPointList {
		ep.Id = uuid.NewString()
		cfg.EndPointList[i] = ep
	}
}

func LoadServerCfg(fileName string) (*ServerConfig, error) {
	data, err := os.ReadFile(fileName)
	if err != nil {
		return nil, err
	}
	cfg := &ServerConfig{}
	err = yaml.Unmarshal(data, cfg)
	if err != nil {
		return nil, err
	}
	cfg.completeEndPointId()
	return cfg, nil
}
